import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ljy_flutter/Inherited/inherited_color_model.dart';
import 'package:ljy_flutter/Inherited/inherited_home_screen.dart';
import 'package:ljy_flutter/Inherited/inherited_widget_state.dart';
import 'package:ljy_flutter/change_notifier_proxy_privoder_ex/models/book_manger_model.dart';
import 'package:ljy_flutter/change_notifier_proxy_privoder_ex/models/book_model.dart';
import 'package:ljy_flutter/change_notifier_proxy_privoder_ex/widgets/change_notifier_proxy_provider_example.dart';
import 'package:ljy_flutter/get/binding/all_controller_binding.dart';
import 'package:ljy_flutter/get/binding/getx_binding_example.dart';
import 'package:ljy_flutter/get/controller_example/GetXControllerLiftcycleMethodExample.dart';
import 'package:ljy_flutter/get/controller_example/getx_controller_example.dart';
import 'package:ljy_flutter/get/getx_services/getx_services.dart';
import 'package:ljy_flutter/get/getx_services/getx_services_example.dart';
import 'package:ljy_flutter/get/international/international_messages.dart';
import 'package:ljy_flutter/get/international/internationalization_example.dart';
import 'package:ljy_flutter/get/mvcdemo/getx_movie_list_widget.dart';
import 'package:ljy_flutter/get/obxCountExample/obx_count_example.dart';
import 'package:ljy_flutter/get/obxCountExample/obx_custom_class.dart';
import 'package:ljy_flutter/ljy_home_channel.dart';
import 'package:ljy_flutter/native_page_channel.dart';
import 'package:ljy_flutter/provider/provider_app.dart';
import 'package:ljy_flutter/provider/provider_counter.dart';
import 'package:ljy_flutter/provider_mvvm_example/widgets/provider_mvvm_example.dart';
import 'package:ljy_flutter/riverpod/riverpod_home_widget.dart';
import 'package:provider/provider.dart';
import 'package:get/get.dart';

void main() async {
  print('flutter main start');

  /// 第二种，provider方式
  // runApp(
  //   MultiProvider(
  //     providers: [
  //       ChangeNotifierProvider(create: (_) => ProviderCounter()),
  //       ChangeNotifierProvider(create: (_) => ProviderName()),
  //       ChangeNotifierProvider(create: (_) => DataProvider()),
  //     ],
  //     child: ProviderApp(),
  //   ),
  // );

  /// 2.1
  // runApp(
  //   MultiProvider(
  //     providers: [
  //       Provider(create: (_) => BookModel()),
  //       ChangeNotifierProxyProvider<BookModel, BookMangerModel>(
  //         create: (_) => BookMangerModel(BookModel()),
  //         update:
  //             (cox, bookModel, bookManagerModel) => BookMangerModel(bookModel),
  //       ),
  //     ],
  //     child: MaterialApp(
  //       debugShowCheckedModeBanner: false,
  //       home: const ChangeNotifierProxyProviderExample(),
  //     ),
  //   ),
  // );

  /// 2.2
  // runApp(
  //   ProviderMvvmExample(),
  // );

  /// 第三种，riverpod方式
  // runApp(ProviderScope(child: RiverpodHomeWidget()));

  /// 第四种，getx方式
  // runApp(ObxCountExample());

  // runApp(ObxCustomClass());

  // runApp(const GetxControllerExampleApp());

  // runApp(
  //   GetMaterialApp(
  //     title: 'GetX Controller Example',
  //     home: Getxcontrollerliftcyclemethodexample(),
  //   )
  // );

  /// 国际化
  /// translations: 国际化配置文件
  /// locale: 设置默认语言，不设置的话为系统当前语言
  /// fallbackLocale: 设置语言不支持时或者配置错误的情况下，使用的语言
  // runApp(
  //   GetMaterialApp(
  //     title: 'International Demo',
  //     theme: ThemeData(
  //       primarySwatch: Colors.blue,
  //     ),
  //     translations: InternationalMessages(),
  //     locale: const Locale('zh', 'CN'),
  //     fallbackLocale: const Locale('zh', 'CN'),
  //     home: InternationalizationExample(),
  //   ),
  // );

  // await initServices();
  // runApp(GetxServicesExample());

  // GetX Binding
  // runApp(
  //   GetMaterialApp(
  //     title: 'GetX Binding Example',
  //     initialBinding: AllControllerBinding(),
  //     home: GetxBindingExample(),
  //   ),
  // );

  runApp(
    GetMaterialApp(
      title: 'GetX Binding Example',
      initialBinding: AllControllerBinding(),
      home: GetxMovieListWidget(),
    ),
  );

  NativePageChannel.init();

  NativePageChannel.getMeasurementUnit().then((value) {
    print("main getMeasurementUnit: $value");
  });

  LjyHomeChannel.instance;
}

Future<void> initServices() async {
  print('初始化服务');
  Get.putAsync(() async => await GetxServicesTool());
  print('服务初始化完成');
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Color _color = Colors.blue;
  void _changeColor() {
    setState(() {
      _color = _color == Colors.blue ? Colors.red : Colors.blue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      routes: {'/inheritedWidget': (context) => InheritedHomeScreen()},
      home: CounterInheritedWidget(
        counter: _counter,
        incrementCounter: _incrementCounter,
        child: ColorInheritedModel(
          color: _color,
          changeColor: _changeColor,
          child: const MyHomePage(title: 'Flutter Demo Home Page'),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });

    LjyHomeChannel.instance.writeData(_counter, "仙道喝可乐2222");
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    final countIW = CounterInheritedWidget.of(context);
    final inheritedModel = ColorInheritedModel.of(context, 'color');

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Column(
        // Column is also a layout widget. It takes a list of children and
        // arranges them vertically. By default, it sizes itself to fit its
        // children horizontally, and tries to be as tall as its parent.
        //
        // Invoke "debug painting" (press "p" in the console, choose the
        // "Toggle Debug Paint" action from the Flutter Inspector in Android
        // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
        // to see the wireframe for each widget.
        //
        // Column has various properties to control how it sizes itself and
        // how it positions its children. Here we use mainAxisAlignment to
        // center the children vertically; the main axis here is the vertical
        // axis because Columns are vertical (the cross axis would be
        // horizontal).
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            color: Colors.yellow[100],
            padding: EdgeInsets.all(10),
            child: Text(
              'You HAVE pushed the button this many times: ${countIW?.counter ?? -1000}',
              style: TextStyle(fontSize: 20, color: Colors.black),
            ),
          ),
          DecoratedBox(
            decoration: BoxDecoration(
              color: Colors.green, // 设置背景色
            ),
            child: Text(
              '$_counter',
              style: TextStyle(fontSize: 20, color: Colors.white),
            ),
          ),
          Container(width: 100, height: 100, color: inheritedModel?.color),
          CupertinoButton(
            child: Text('修改颜色'),
            onPressed: () {
              inheritedModel?.changeColor();
            },
          ),
          Row(
            children: [
              TextButton(
                onPressed: () {
                  print('文字按钮被点击');
                  countIW?.incrementCounter();
                },
                child: Text('文字按鈕'),
              ),
              ElevatedButton(
                onPressed: () {
                  print('InheritedWidget状态管理  $context');

                  // Navigator.pushNamed(context, '/inheritedWidget');
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => HomePushScreen()),
                  );
                },
                child: Text('InheritedWidget状态管理'),
              ),
            ],
          ),
          HomeSubScreen(),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class HomeSubScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final inheritedModel = ColorInheritedModel.of(context, 'color');

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(width: 100, height: 100, color: inheritedModel?.color),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: inheritedModel?.changeColor,
          child: Text('Change Color in Sub Screen'),
        ),
      ],
    );
  }
}

// 跳转出来的
class HomePushScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final inheritedModel = ColorInheritedModel.of(context, 'color');
    print('${inheritedModel?.color}, ${inheritedModel?.changeColor}，$context');

    return Scaffold(
      appBar: AppBar(title: Text('Sub Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(width: 100, height: 100, color: inheritedModel?.color),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: inheritedModel?.changeColor,
              child: Text('Change Color in Sub Screen'),
            ),
          ],
        ),
      ),
    );
  }
}
